package com.sprouting.ops.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sprouting.ops.annotations.invoke.IdempotentSingle;
import com.sprouting.ops.interfaces.AddGroup;
import com.sprouting.ops.interfaces.ConstantBase;
import com.sprouting.ops.interfaces.UpdGroup;
import com.sprouting.ops.model.*;
import com.sprouting.ops.model.qo.AvailableDependQo;
import com.sprouting.ops.model.qo.OpsProductDependQo;
import com.sprouting.ops.model.qo.OpsProductQo;
import com.sprouting.ops.model.vo.AvailableDependVo;
import com.sprouting.ops.model.vo.OpsProductDependVo;
import com.sprouting.ops.service.*;
import com.sprouting.ops.utils.CheckTool;
import com.sprouting.ops.utils.EntityTool;
import com.sprouting.ops.utils.IdTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品(OpsProduct)() 表控制层
 *
 * @author ：lx（长沙麓谷）
 * @date 创建时间：2025-06-01 15:38:08
 */
@Slf4j
@RestController
@RequestMapping("opsProduct")
public class OpsProductController {

    @Resource
    private OpsProductService opsProductService;
    @Resource
    private DromaraFileStorageService dromaraFileStorageService;
    @Resource
    private OpsProductDependService opsProductDependService;
    @Resource
    private OpsAppService opsAppService;
    @Resource
    private OpsComponentService opsComponentService;


    /**
     * 获取可选的依赖
     * @param query 查询参数
     * @return
     */
    @PostMapping("getAvailableDepend")
    public ResultJson getAvailableDepend(@Validated AvailableDependQo query){
        Integer type = query.getType();
        Page page = query.getPage();

        OpsProductDependQo dependQo = new OpsProductDependQo();
        dependQo.setProductId(query.getProductId());
        Page<OpsProductDependVo> excludePageList = opsProductDependService.getListPage(new Page(1, 999), dependQo);
        List<OpsProductDependVo> records = excludePageList.getRecords();

        // 排除的绑定类型
        List<String> excludeList = new ArrayList<>();

        if (CollUtil.isNotEmpty(records)){
            excludeList = records.stream().map(OpsProductDepend::getBindId).collect(Collectors.toList());
        }

        Page<AvailableDependVo> list = null;
        if (ConstantBase.ProductDependType.PROJECT.equals(type)){
            excludeList.add(query.getProductId());
            list = opsProductService.getAvailableDepend(page, excludeList, query);

        } else if (ConstantBase.ProductDependType.APP.equals(type)){
            list = opsAppService.getAvailableDepend(page, excludeList, query);

        } else if (ConstantBase.ProductDependType.COMPONENT.equals(type)){
            list = opsComponentService.getAvailableDepend(page, excludeList, query);

        } else {
            return ResultJson.errorCheck();
        }

        return ResultJson.success(list);
    }

    /**
     * 分页查询产品
     * @param query 查询参数
     * @return
     */
    @PostMapping("getListPage")
    public ResultJson getListPage(OpsProductQo query){
        if (query == null){
            query = new OpsProductQo();
        }
        Page page = query.getPage();
        return ResultJson.success(opsProductService.getListPage(page, query));
    }

    /**
     * 删除产品
     * @param id 产品id
     * @return
     */
    @PostMapping("delOpsProduct")
    @IdempotentSingle
    public ResultJson delOpsProduct(String id){
        if (CheckTool.checkNull(id)){
            return ResultJson.errorCheck();
        }

        OpsProduct product = opsProductService.getById(id);
        if (product == null){
            return ResultJson.success();
        }

        DromaraFileStorage opsUploadFile = dromaraFileStorageService.delFileBefore(product.getIco());
        opsProductService.delOpsProduct(product, opsUploadFile);
        return ResultJson.success();
    }

    /**
     * 更新产品
     * @param bo 修改参数
     * @return
     */
    @PostMapping("updOpsProduct")
    @IdempotentSingle
    public ResultJson updOpsProduct(@Validated(UpdGroup.class) OpsProduct bo){
        String msg = checkOpsProduct(bo);
        if (msg != null){
            return ResultJson.error(msg);
        }

        // 查询到旧的
        OpsProduct oldProduct = opsProductService.getById(bo.getId());
        DromaraFileStorage[] uploadFileArray = dromaraFileStorageService.updFileBefore(bo.getIco(), oldProduct.getIco(), bo.getId(), ConstantBase.FileSourceType.PRODUCT_ICO);

        EntityTool.updBase(bo);
        opsProductService.updOpsProduct(bo, uploadFileArray);
        return ResultJson.success(bo);
    }

    /**
     * 保存产品
     * @param bo 保存参数
     * @return
     */
    @PostMapping("saveOpsProduct")
    @IdempotentSingle
    public ResultJson saveOpsProduct(@Validated(AddGroup.class) OpsProduct bo){
        String msg = checkOpsProduct(bo);
        if (msg != null){
            return ResultJson.error(msg);
        }

        // 处理图片
        DromaraFileStorage opsUploadFile = dromaraFileStorageService.toProductionBefore(bo.getIco(), bo.getId(), ConstantBase.FileSourceType.PRODUCT_ICO);

        bo.setId(IdTool.getId());
        EntityTool.saveBase(bo);
        opsProductService.saveOpsProduct(bo, opsUploadFile);
        return ResultJson.success(bo);
    }


    /**
     * 产品数据校验
     * @param bo 产品 校验数据
     * @return 非null则有错误
     */
    private String checkOpsProduct(OpsProduct bo){
        if (bo.getStatus() == null){
            bo.setStatus(ConstantBase.ProjectState.DEV);
        }
        if (bo.getImportance() == null){
            bo.setImportance(ConstantBase.Importance.IMPORTANT);
        }
        if (bo.getCommon() == null){
            bo.setCommon(ConstantBase.YesOrNo.NO);
        }

        return null;
    }

}
